package com.eascs.admin.o2o.generation.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.o2o.generation.service.O2oGenerationService;
import com.eascs.admin.o2o.generation.vo.O2oGenerationVo;
import com.eascs.admin.o2o.internal.controller.PayMentViewController;
import com.eascs.app.dao.PageResult;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Controller
@RequestMapping("/generation")
public class O2oGenerationController extends BaseMasterViewController {
	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "generation");
	}

	@Autowired
	O2oGenerationService generationService;
	@Reference
	SysOrgService sysOrgService;

	@RequestMapping("/index")
	public String index(O2oGenerationVo vo) {
		vo.setPageSize(10);
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		String url = "/generation/index";
		String reporto2ourl = "/generation/download";
		String billNum = vo.getBillNum() == null ? "" : vo.getBillNum();
		String loanBillCode = vo.getLoanBillCode() == null ? "" : vo.getLoanBillCode();
		String loanUserName = vo.getLoanUserName() == null ? "" : vo.getLoanUserName();
		String provinceCode = vo.getProvinceCode() == null ? "" : vo.getProvinceCode();
		String operName = vo.getOperName() == null ? "" : vo.getOperName();
		String ltdName = vo.getLtdName() == null ? "" : vo.getLtdName();
		String createStartTime = vo.getCreateStartTime() == null ? "" : vo.getCreateStartTime();
		String createEndTime = vo.getCreateEndTime() == null ? "" : vo.getCreateEndTime();
		String flowStatus = vo.getFlowStatus() == null ? "" : vo.getFlowStatus();
		url = UrlUtil.appendUrl(url, "billNum", billNum);
		url = UrlUtil.appendUrl(url, "loanBillCode", loanBillCode);
		url = UrlUtil.appendUrl(url, "loanUserName", loanUserName);
		url = UrlUtil.appendUrl(url, "provinceCode", provinceCode);
		url = UrlUtil.appendUrl(url, "operName", operName);
		url = UrlUtil.appendUrl(url, "createStartTime", createStartTime);
		url = UrlUtil.appendUrl(url, "createEndTime", createEndTime);
		url = UrlUtil.appendUrl(url, "flowStatus", flowStatus);
		url = UrlUtil.appendUrl(url, "ltdName", ltdName);
		url = url + "&pageIndex=";
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "billNum", billNum);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanBillCode", loanBillCode);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanUserName", loanUserName);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "provinceCode", provinceCode);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "operName", operName);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "createStartTime", createStartTime);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "createEndTime", createEndTime);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "flowStatus", flowStatus);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "ltdName", ltdName);
		PageResult<Object[]> pageResult = generationService.findByPage(vo);
		String titles[] = { "单据号", "贷款单号", "借款人", "放款日期", "信贷经理", "省区", "经营平台", "打款金额", "打款时间", "创建时间", "流程状态" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null, null, null, null, null, new SelectDataOption("O2O_BILLSTATUS") };
		Button[] titleButtons = new Button[] { ButtonHelper.createAjaxButton(null, "/rgeneration/approl_detail?id=") };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, url);
		o2oPagingInfo.setFirstRenderColumnIndex(2);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setTitleButtons(titleButtons);
		ViewContext.put("paginationInfo", o2oPagingInfo);
		ViewContext.put("vo", vo);
		ViewContext.put("reporto2ourl", reporto2ourl);
		return "generation/index";
	}
	
	@RequestMapping("/download")
	public void dowanload(O2oGenerationVo vo, HttpServletResponse httpServletResponse, HttpServletRequest request) {
		vo.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = generationService.findByPageExport(vo);
		String path = PayMentViewController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/generation.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "代还款查询数据.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oGenerationController.class.getResourceAsStream("/excelTemplate/generation.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
}
